﻿/*
 * Author: xianmao
 * Date: 2013-02-19
 * 
 */


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Collections;

namespace Utility
{
    public class Tool
    {
        public const char space = ' ';
        /// <summary>
        /// 获取指定个数据的普通空格
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        static public string GetSpace(int n)
        {
            return new string(space, n);
        }

        /// <summary>
        /// 获取指定个数据的Tab
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        static public string GetTab(int n)
        {
            return new string(space, n * 4);
        }

        /// <summary>
        /// 获取文件的后缀名（小写）
        /// </summary>
        /// <param name="FullPath"></param>
        /// <returns></returns>
        static public string GetFileExtension(string FullPath)
        {
            if (FullPath.IndexOf('.') < 0) return "";
            return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="slen"></param>
        /// <param name="substitute"></param>
        /// <returns></returns>
        public static string CutString(string str, int slen, string substitute = "...")
        {
            int i = 0, j = 0;
            foreach (char chr in str)
            {
                if ((int)chr > 127)
                {
                    i += 2;
                }
                else
                {
                    i++;
                }
                if (i > slen)
                {
                    str = str.Substring(0, j) + substitute;
                    break;
                }
                j++;
            }
            return str;
        }

        /// <summary>
        /// 获取短日期
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetShortDate(string str, bool shorter = false)
        {
            DateTime date = DateTime.Parse(str);
            if (shorter) return date.ToString("MM-dd");
            return date.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 得到SHA256加密后的字符串
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string SHA256Encrypt(string plainText)
        {
            SHA256Managed _sha256 = new SHA256Managed();
            byte[] _cipherText = _sha256.ComputeHash(Encoding.Default.GetBytes(plainText));
            return Convert.ToBase64String(_cipherText);
        }

        public static string ExstractUrlFormImg(string s)
        {
            Match m = Regex.Match(s, "src=\\\"(?<value>.*?)\\\"");
            if (m.Success)
            {
                return m.Groups["value"].Value;
            }
            return string.Empty;
        }
        /// <summary>
        /// 网站日志保存时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int TimeSpanLog(DateTime time)
        {
            TimeSpan timespan = DateTime.Now - time;
            int days = timespan.Days;
            return days;
        }
        ///字节的转换
        public static string ByteConversionGBMBKB(string size)
        {
            const int GB = 1024 * 1024 * 1024;//定义GB的计算常量
            const int MB = 1024 * 1024;//定义MB的计算常量
             const int KB = 1024;//定义KB的计算常量
           long ksize = Convert.ToInt64(size);
             if (ksize / GB >= 1)//如果当前Byte的值大于等于1GB
                 return (Math.Round(ksize / (float)GB, 2)).ToString() + "GB";//将其转换成GB
             else if (ksize / MB >= 1)//如果当前Byte的值大于等于1MB
                 return (Math.Round(ksize / (float)MB, 2)).ToString() + "MB";//将其转换成MB
             else if (ksize / KB >= 1)//如果当前Byte的值大于等于1KB
                 return (Math.Round(ksize / (float)KB, 2)).ToString() + "KB";//将其转换成KGB
             else
                 return ksize.ToString() + "Byte";//显示Byte值
        }
        /// <summary>  
        /// 获取文章中图片地址的方法  
        /// </summary>  
        /// <param name="substance">文章内容</param>  
        /// <param name="regstr">正则表达式</param>  
        /// <param name="keyname">关键属性名</param>  
        /// <returns></returns>  
        public static ArrayList getImgUrl(string substance)
        {
            ArrayList resultStr = new ArrayList();
            Regex r = new Regex(@"<IMG[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>", RegexOptions.IgnoreCase);
            MatchCollection mc = r.Matches(substance);

            foreach (Match m in mc)
            {
                resultStr.Add(m.Groups["src"].Value.ToLower());
            }
            if (resultStr.Count > 0)
            {
                return resultStr;
            }
            else
            {
                //没有地址的时候返回空字符  
                resultStr.Add("");
                return resultStr;
            }
        }
        /// <summary>
        /// 移除html标记
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string RemoveHtml(string html)
        {
            string result = html;

            MatchCollection matches = objReg.Matches(html);
            foreach (Match match in matches)
            {
                result = result.Replace(match.Value, string.Empty);
            }
            return HttpUtility.HtmlEncode(result.Replace("&nbsp;", " "));
        }
        private static readonly Regex objReg = new Regex("<.+?>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);
    }
}
